import { Handler } from "$fresh/server.ts";
import { getCookies } from "$std/http/cookie.ts";
import { decodeBase64 } from "$std/encoding/base64.ts";
import { CurrentAES } from "~/tools/crypto/server.ts";
import { ConsoleHandler, getLogger, setup } from "logger";
import dayjs from "dayjs";
setup({
  handlers: {
    default: new ConsoleHandler("INFO", {
      formatter: (record) => {
        return `api/admin middleware: ${
          dayjs(record.datetime).format("YYYY-MM-DD HH:mm:ss")
        } [${record.levelName}] ${record.msg}`;
      },
    }),
  },
});
const dl = getLogger();
// 接口白名单列表
const whiteList: Array<string> = [];
// 加密排除名单列表
const encryptExcludeList: string[] = [];
const nobodymethods = ["GET", "HEAD"];
const decoder = new TextDecoder();
/**
 * 该目录接口专用于本站管理使用
 * todo：还未接入authing,函数内容暂未完善
 * @param req
 * @param ctx
 * @returns
 */
export const handler: Handler<{ iv: string; data: string }> = async (
  req,
  ctx,
) => {
  if (
    !nobodymethods.some((i) => req.method === i) &&
    req.headers.get("Content-Type")?.toLowerCase().includes("application/json")
  ) {
    const reqJson = await req.clone().json();

    ctx.data = reqJson;
  }

  // 白名单列表
  if (whiteList.includes(ctx.url.pathname)) {
    const resp = await ctx.next();
    return resp;
  }
  const cookies = getCookies(req.headers);

  if (!cookies["t"]) {
    dl.warn("没有访问令牌");
  }

  if (encryptExcludeList.includes(ctx.url.pathname)) {
    const resp = await ctx.next();
    resp.headers.append("Content-Type", "application/json");
    return resp;
  }

  const { data, iv } = ctx.data;

  return CurrentAES.decrypt(decodeBase64(data), decodeBase64(iv))
    .then((plaintext) => {
      const info = decoder.decode(plaintext);
      ctx.state = JSON.parse(info);
    }).then(async () => {
      const resp = await ctx.next();
      return resp;
    });
};
